nice_things/text/substitute_expression.sh
substitute_expression
Since 0.3.0 · Source
import "{ substitute_expression }" from nice_things/text/substitute_expression.sh
Synopsissubstitute_expression <expression> <replacement> [<text>]
Configuration
–
Description
Substitute every match of the <expression> in <text> with the <replacement> string, and print the result. If the <text> parameter is omitted, text will be read from stdin.
This function uses only shell builtins and has no external dependencies (e.g. on sed). This is slower than using sed on large inputs, but can be faster on many invocations with small inputs, since it avoids forking a new process.
Warning
Escaping special characters by prepending a backslash character does not work on mksh. For a portable way to match them literally, use square-bracket character classes instead—e.g.
[[]and[\\]instead of\[and\\.
Note
Matching expressions as done in this function is slow. If you want to substitute single characters, consider using the faster
substitute_charactersfunction instead.
Options
–
Operands
<expression>: A shell expression, as used in acasestatement.<replacement>: A string to replace any matched text.<text>: The text to operate on. If omitted, stdin will be used.
Stdin
The text will be read from stdin if the <text> parameter is omitted.
Stdout
The result will be printed to stdout.
Stderr
–
Exit status0: Successful completion.
Abort
–
Usage examples
lf='
'
# Decode escaped '\\' to a single backslash character, read from stdin
assign decoded_text substitute_expression '[\\][\\]' '\' </path/to/file
# Decode escaped '\n' to line-feed characters
assign decoded_text substitute_expression '[\\]n' "$lf" "$decoded_text"